package com.softserveinc.moviedbapp.parser;

import android.util.Log;

import com.softserveinc.moviedbapp.connection.MovieDBConnectionException;
import com.softserveinc.moviedbapp.model.Movie;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class JSONParserMovieBrowse implements IMovieDBMethodBrowseSearch {

	private static final String TAG = JSONParserMovieBrowse.class.getSimpleName();

	@Override
	public List<Movie> parse(final InputStream is) throws MovieDBConnectionException {
		List<Movie> movies = new ArrayList<Movie>();
		String jsonString = "";
		try {
			jsonString = JSONHelper.convertStreamToString(is);
		} catch (IOException e) {
			Log.e(TAG, "Parsing MOVIE.BROWSE JSON FAILED.", e);
			throw new MovieDBConnectionException("SocketTimeoutException");
		}
		/* start parsing */
		try {
			JSONArray jsonArray = new JSONArray(jsonString);

			for (int i = 0; i < jsonArray.length(); i++) {
				Movie movie = new Movie();

				JSONObject jsonMovie = jsonArray.getJSONObject(i);

				/* set easily accessible data */
				movie.setName(jsonMovie.getString("name"));
				movie.setCertification(jsonMovie.getString("certification"));
				movie.setMovieId(jsonMovie.getInt("id"));
				movie.setUrl(jsonMovie.getString("url"));
				movie.setRating(jsonMovie.getDouble("rating"));
				movie.setLastModifiedAt(jsonMovie.getString("last_modified_at"));
				movie.setReleased(jsonMovie.getString("released"));
				movie.setVotes(jsonMovie.getInt("votes"));

				/* get the movie poster url */
				JSONArray posters = jsonMovie.getJSONArray("posters");
				for (int j = 0; j < posters.length(); j++) {
					JSONObject posterUrlObject = posters.getJSONObject(j).getJSONObject("image");

					if (posterUrlObject.getString("size").equals("thumb")) {
						movie.setThumbPosterUrl(posterUrlObject.getString("url"));
						break;
					}
				}
				movies.add(movie);
				Log.d(TAG, "JSON Parsing succeeded, movie\n" + movie.toString());

			}

		} catch (JSONException e) {
			Log.e(TAG, "JSON MOVIE LIST Parsing failed NOTHING FOUND.", e);
			throw new MovieDBConnectionException("End of input at character 0 of ");
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				Log.e(TAG, "unable to close input stream", e);
			}
		}
		return movies;
	}
}
